<?php
/**
 * 模型代码生成器
 */
namespace app\common\logic;

use think\helper\Str;

class CmsBuildLogic
{
    private $TAB = "    ";

    /**
     * 生成验证器
     */
    public function buildValidate($mid)
    {
        $moudle = \think\Db::table('cms_moudle')->find($mid);
        $fields = \think\Db::table('cms_field')->where('mid', $mid)->order('field_sort')->select();
        foreach ($fields as $v) {
            if ($v['validate_scene'] > 0 && !empty($v['validate'])) {
                $validate = json_decode($v['validate'], true);
                $rule[]   = str_repeat($this->TAB, 2) . "'" . $v['field_name'] . "|" . $v['title'] . "'=>'" . implode('|', $validate) . "'";
                if ($v['validate_scene'] == 1) {
                    $sceneAdd[] = "'" . $v['field_name'] . "'";
                }
                if ($v['validate_scene'] == 2) {
                    $sceneEdit[] = "'" . $v['field_name'] . "'";
                }
                if ($v['validate_scene'] == 3) {
                    $sceneAdd[]  = "'" . $v['field_name'] . "'";
                    $sceneEdit[] = "'" . $v['field_name'] . "'";
                }
            }
        }
        $moudleName = Str::studly($moudle['table_name']);
        $rule       = implode(',' . PHP_EOL, $rule);
        $sceneAdd   = implode(',', $sceneAdd);
        $sceneEdit  = implode(',', $sceneEdit);
        $str        = <<<CODE
namespace app\\common\\validate;

use think\\Validate;

class {$moudleName}Validate extends Validate {
    // 验证规则
    protected \$rule = [
{$rule}
    ];
    //验证场景
    protected \$scene = [
        'add'  =>  [{$sceneAdd}],
        'edit'  =>  [{$sceneEdit}],
    ];
}
CODE;
        return $str;
    }

    /**
     * 生成模型
     */
    public function buildModel($mid)
    {
        $moudle  = \think\Db::table('cms_moudle')->find($mid);
        $fields  = \think\Db::table('cms_field')->where('mid', $mid)->order('field_sort')->select();
        $typeArr = [];
        $getAttr = [];
        foreach ($fields as $v) {
            //json类型转换
            if (in_array($v['field_type'], ['images', 'files'])) {
                $typeArr[] = str_repeat($this->TAB, 2) . "'" . $v['field_name'] . "'=>'json'";
            }
            //数字类型转换
            if ($v['field_type'] == 'number') {
                $set = json_decode($v['set'], true);
                if ($set['field_type'] == 'decimal') {
                    $typeStr = 'float';
                } else {
                    $typeStr = 'integer';
                }
                $typeArr[] = str_repeat($this->TAB, 2) . "'" . $v['field_name'] . "'=>'" . $typeStr . "'";
            }
            //日期类型转换
            if ($v['field_type'] == 'datetime') {
                $set = json_decode($v['set'], true);
                switch ($set['format']) {
                    case 0:
                        $format = 'Y-m-d H:i:s';
                        break;
                    case 1:
                        $format = 'Y-m-d';
                        break;
                    case 2:
                        $format = 'H:i:s';
                        break;
                }
                $typeArr[] = str_repeat($this->TAB, 2) . "'" . $v['field_name'] . "'=>'timestamp:" . $format . "'";
            }
            //富文本读取器
            if ($v['field_type'] == 'editor') {
                $editor = $this->TAB . 'protected function get' . Str::studly($v['field_name']) . 'Attr($value,$data) {' . PHP_EOL;
                $editor .= str_repeat($this->TAB, 2) . 'return stripslashes(htmlspecialchars_decode($value));' . PHP_EOL;
                $editor .= $this->TAB . '}';
                $getAttr[] = $editor;
            }
        }
        $moudleName = Str::studly($moudle['table_name']);
        $tableName  = $moudle['table_name'];
        $typeArr    = implode(',' . PHP_EOL, $typeArr);
        $getAttr    = implode(',' . PHP_EOL, $getAttr);
        $str        = <<<CODE
namespace app\common\model;
use think\model\Merge;
use think\Request;
class {$moudleName}Model extends Merge {
    protected \$name = '{$tableName}'; //定义栏目表
    //开启自动写入时间戳
    protected \$autoWriteTimestamp = true;
    //类型自动转换
    protected \$type = [
{$typeArr}
    ];
    // 定义自动完成的属性
    protected \$auto   = []; //新增修改
    protected \$insert = ['uid']; //插入
    protected \$update = []; //修改
    // 定义关联模型列表
    protected \$relationModel = ['{$moudleName}Data'];
    // 定义关联外键
    protected \$fk = 'aid';
    // 为混淆字段定义映射
    protected \$mapFields = [
        'aid' => '{$tableName}.aid',
        'data_aid' => '{$moudleName}Data.aid',
    ];
    /*读取器*/
    protected function getStatusTextAttr(\$value,\$data) {
        \$status = [
            0 => '<span class="label label-warning">待审</span>',
            1 => '<span class="label label-success">已审</span>'
        ];
        return \$status[\$data['status']];
    }
    protected function getContentAttr(\$value) {
        return stripslashes(htmlspecialchars_decode(\$value));
    }
    /*修改器*/
    protected function setDescriptionAttr(\$value,\$data){
        if(empty(\$value)){
            \$str = del_html(html_out(\$data['content']));
            if(empty(\$str)){
                return \$data['title'];
            }
            return substr(\$str,0,240);
        }
        return \$value;
    }
    protected function setFlagAttr(\$value,\$data){
        if(empty(\$value)){
            return '';
        }else{
            return implode(',',\$value);
        }
    }
    
    protected function setUidAttr(\$value){
        \$request = Request::instance();
        \$moudle = \$request->module();
        return is_login(\$moudle);
    }
}
CODE;
        return $str;
    }

}
